package cj.web.login.controllers;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cj.utils.Base64;
import cj.utils.ReadConfigProperties;
import cj.web.admin.domain.UserInfo;

/**
 * Base
 * @author Administrator
 *
 */
public class BaseController{
	
	protected final static String imgkzm = ".gif";
	
	protected static final String cityWuhan="武汉市";
	
	protected static final String shareUrl=ReadConfigProperties.getValue("shareUrl");

	public UserInfo returnSessionObj(HttpServletRequest request)
	{
		//初始化对象
		UserInfo obj =new UserInfo();
		//Cookie中获取request  by account
		Cookie ck = getCookieByName(request, "account");
		Cookie ckname = getCookieByName(request, "name");
		Cookie ckuserId = getCookieByName(request, "userId");
		obj.setAccount(ck.getValue());
		obj.setId(Integer.parseInt(ckuserId.getValue()));
		obj.setName(Base64.getFromBase64(ckname.getValue()));
		return obj;
	}
	
	/**
     * 根据名字获取cookie
     * @param request
     * @param name cookie名字
     * @return
     */
    public Cookie getCookieByName(HttpServletRequest request,String name){
        Map<String,Cookie> cookieMap = ReadCookieMap(request);
        if(cookieMap.containsKey(name)){
            Cookie cookie = (Cookie)cookieMap.get(name);
            return cookie;
        }else{
            return null;
        }   
    }
      
    /**
     * 添加Cookie
     * @param response
     * @param name
     * @param value
     */
    public void addCookie(HttpServletResponse response,String name,String value){
        Cookie cookie = new Cookie(name.trim(), value.trim());
        cookie.setPath("/");
        response.addCookie(cookie);
    }  
      
    /**
     * 将cookie封装到Map里面
     * @param request
     * @return
     */
    private  Map<String,Cookie> ReadCookieMap(HttpServletRequest request){  
        Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
        Cookie[] cookies = request.getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
}
